<template>
  <div class="activity-body">
    <div class="activity-ad">
      <img :src="prefixImg+ openedActList.detailBannerImgUrl" alt="" @error="catchErrorImage($event)">
    </div>
    <div ref="containerRef" class="knife_container">
      <div class="brand_container" v-for="(item, index) in brandList" :ref="`brandRef_${item.name}`">
        <div class="brand-name-container" :key="item.name">
          <div class="brand-item">
            <img class="brand-img" :src="prefixImg + item.image" :alt="item.name"/>
            <span class="brand-name">{{item.name}}</span>
            <span class="brand-discount">({{(item.discount * 10).toFixed(2)}}折优惠)</span>
          </div>
          <router-link :to="{name: 'ProductList', query: {brand: item.id, collbrand: true}}" class="view-more">查看更多></router-link>
        </div>
        <brandProductItem
          class="product-box"
          :product="brandGoodsList[index]"
          v-if="brandGoodsList[index] && brandGoodsList[index].length > 0"
          :fielsStatus="fielsStatus"
          :actDate="actDate"
          :actTime="actTime"
          :discount="item.discount">
        </brandProductItem>
      </div>
      <!-- 活动规则 -->
      <div class="rule-box activity-wrap" v-if="openedActList.content">
        <div class="rule-title">活动规则</div>
        <div class="rule-content" v-html="openedActList.content">
        </div>
      </div>
    </div>
    <!-- 左侧导航 -->
    <div class="floor_nav_box" style="width: auto;" v-if="isPosShow && brandNum > 1">
      <a class="discount-item" @click="srollToBrand(item.name)" :class="{'on': index === currentPosInd}"  v-for="(item, index) in brandList">{{item.name}}</a>
    </div>
  </div>
</template>

<script>
import { getGoodsListByKeyword } from '@/service/get-data'
import { Pagination, Row, Input } from 'element-ui'
import { brandProductItem } from '@/components/index'
import { mapState, mapActions } from 'vuex'
// import { countDown } from '@/tool/tool'
import { prefixImg } from '@/tool/index'
import _ from 'lodash'
export default {
  components: {
    elPagination: Pagination,
    elRow: Row,
    elInput: Input,
    brandProductItem
  },
  data () {
    return {
      prefixImg,
      timerresult: '',
      timerText: '',
      fielsStatus: 0, // 活动状态  0：未开启， 1： 进行中 2 ：活动结束
      openedActList: {
        detailBannerImgUrl: null
      },
      actDate: '',
      actTime: '',
      categoryName: '',
      categoryList: [],
      categoryIds: '',
      otherList: [],
      others: '',
      collapseCate: false, // 分类是否展开
      collapseBrand: false, // 品牌是否展开
      collapseOther: false, // 其他属性是否展开
      goodsPro: {
        page: 1, // 商品列表的页码
        number: 10 // 商品列表一页的数量
      },
      amount: 0,
      searchInput: '',
      keyword: '',
      selectType: '', // 主选0为品牌，1为类目
      goodsObj: {}, // 商品列表
      brandHeight: '', // 品牌的高度
      cateHeight: 62, // 类目的高度
      otherHeight: '', // 其他属性的高度

      brandList: [], // 活动品牌列表
      refposition: [],
      currentPosInd: 0,
      isPosShow: false,
      brandGoodsList: []  // 品牌的商品数组
    }
  },
  computed: {
    ...mapState({
      username: state => state.user.username
    }),
    brandNum () {
      return this.brandList && this.brandList.length
    }
  },
  methods: {
    ...mapActions(['fetchBrandActivity']),
    catchErrorImage (e) {
      e.target.src = require('img/bargainhead.png')
    },
    // 位置数组
    getPosition () {
      const offsetContainer = this.$refs.containerRef && this.$refs.containerRef.offsetTop
      const scrollH = document.body.scrollHeight
      // const brand = this.$refs.brandRef && this.$refs.brandRef.offsetTop
      // const hotsale = this.$refs.hotsaleRef && this.$refs.hotsaleRef.offsetTop
      // const price = this.$refs.priceRef && this.$refs.priceRef.offsetTop
      // const newpro = this.$refs.newproRef && this.$refs.newproRef.offsetTop
      let refList = []
      this.brandList.map((refItem, index) => {
        let offsetTop = this.$refs[`brandRef_${refItem.name}`][0] && this.$refs[`brandRef_${refItem.name}`][0].offsetTop
        refList.push(offsetTop + offsetContainer)
      })
      refList.push(scrollH)
      this.refposition = refList
    },
    // 导航
    srollToBrand (name) {
      let ref = this.$refs[`brandRef_${name}`][0]
      ref.scrollIntoView({behavior: 'smooth', block: 'start'})
    },
    debounceActive () {
      this.debouncescroll = _.debounce(this.handleScroll, 200, {leading: true, trailing: false})
    },
    handleScroll () {
      const scroll = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
      const len = this.refposition.length
      if (scroll < 610) {
        this.isPosShow = false
        this.currentPosInd = 0
        return
      }
      for (let i = 1; i < len; i++) {
        if (scroll < this.refposition[i]) {
          this.currentPosInd = i - 1
          this.isPosShow = true
          break
        }
      }
    },
    getBrandsProduct () {
      return new Promise((resolve, reject) => {
        this.fetchBrandActivity().then(res => {
          this.openedActList = null
          this.openedActList = (res && res.voList[0]) || {}
          // 周周活动结束
          if (!('id' in this.openedActList)) {
            this.showActivity = false
            return
          }
          let _str = this.openedActList.startTime.split(' ')[0].split('-')
          let _time = this.openedActList.endTime.split(' ')[1].substr(0, 5)
          this.actDate = `${_str[1]}月${_str[2]}日`
          this.actTime = _time
          // 品牌列表
          this.brandList = this.openedActList.brandVOS
          let startTimeParm = this.openedActList.startTime
          let endTimeParm = this.openedActList.endTime
          const starTimeStamp = (new Date(startTimeParm.replace(/-/g, '/'))).getTime()
          const endTimeStamp = (new Date(endTimeParm.replace(/-/g, '/'))).getTime()
          let nowTime = (new Date()).getTime()
          // 周周活动开始
          if (nowTime > starTimeStamp && nowTime <= endTimeStamp) {
            this.timerText = '距结束'
            this.fielsStatus = 1
          }
          // 周周活动还未开始
          if (nowTime < starTimeStamp) {
            this.timerText = '距开始'
            this.fielsStatus = 0
          }
          // 周周活动结束
          if (nowTime > endTimeStamp) {
            this.fielsStatus = 2
          }
          resolve(this.openedActList.brandVOS)
        })
      })
    },
    // 关键字搜索商品
    getBrandGoods (brandId) {
      return new Promise(async (resolve, reject) => {
        let res = await getGoodsListByKeyword(this.goodsPro.page, this.goodsPro.number, this.searchInput, this.categoryIds, brandId, this.others, false, this.username)
        res = res.data
        if (res.resultCode && res.resultCode === 2000) {
          resolve(res.data.list)
          // this.brandGoodsList.push(res.data.list)
        }
      })
    },
    // 关键字搜索商品
    fetchGoodsListByKeyword (brandlist) {
      let promises = brandlist.map((item, index) => {
        return this.getBrandGoods(item.id)
      })
      Promise.all(promises).then((allList) => {
        this.brandGoodsList = allList
      })
    },
    // 商品列表分页
    handlePage (page) {
      this.goodsPro.page = page
      this.fetchGoodsListByKeyword()
    },
    // 规格页码选择
    page (currentPage) {
      this.searchPro.page = currentPage
      this.fetchProSpecList()
    },
    // 关键字高亮
    changeColor (resultsList) {
      resultsList.map((item, index) => {
        if (this.searchInput && this.searchInput.length > 0) {
          let replaceReg = new RegExp(this.searchInput, 'g')
          let repalceStr = `<span class="color-red">${this.searchInput}</span>`
          resultsList[index].originname = item.name
          resultsList[index].name = item.name.replace(replaceReg, repalceStr)
          resultsList[index].other = item.other.replace(replaceReg, repalceStr)
          resultsList[index].brandName = item.brandName.replace(replaceReg, repalceStr)
        }
      })
      this.goodsObj.list = []
      this.goodsObj.list = resultsList
    },
    getAllData () {
      this.fetchGoodsListByKeyword()
      // this.fetchCategoryList()
      // this.fetchOtherListByKeyword()
    }
  },
  mounted () {
    let vm = this
    this.getBrandsProduct().then(res => {
      vm.fetchGoodsListByKeyword(res)
    })
    this.debounceActive()
    setTimeout(() => {
      vm.getPosition()
    }, 2000)
    window.addEventListener('scroll', this.handleScroll, false)
    // this.$nextTick(() => {
    //   vm.getPosition()
    // })
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  beforeRouteLeave (to, from, next) {
    this.globalTimer = null
    clearInterval(this.globalTimer)
    next()
  },
  watch: {
     // 高度监测
    otherList: {
      handler (newValue, oldValue) {
        this.$nextTick(() => {
          if (this.$refs.refProperty) {
            let height = this.$refs.refProperty.offsetHeight
            this.otherHeight = height
          }
        })
      },
      immediate: true
    },
    categoryList: {
      handler (newValue, oldValue) {
        this.$nextTick(() => {
          if (this.$refs.refCategory) {
            let height = this.$refs.refCategory.offsetHeight
            this.cateHeight = height
          }
        })
      },
      immediate: true
    }
  },
  filters: {
  }
}
</script>

<style lang="scss" scoped>
.activity-body{
  background:#FDE7DE;
  padding-bottom: 30px;
}
.activity-ad{
  position: relative;
  width: 100%;
  height: 580px;
  margin-bottom: 30px;
  // background-image: url("./img/brandsale_banner.png");
  // background-repeat: no-repeat;
  // background-size: cover;
  // background-position: center;
  img{
    width: 100%;
    height: 100%;
    transform: translate(-50%);
    position: absolute;
    left: 50%;
  }
}
.brand_container{
  margin-bottom: 20px;
}
.brand-name-container{
  margin-bottom: 10px;
  border: 2px solid #FF3535;
  box-sizing: border-box;
  padding: 10px 20px;
  height: 60px;
  line-height: 40px;
  text-align: center;
  background: #fff;
  .brand-item{
    display: inline-block;
    .brand-img{
      height: 40px;
      padding-right: 10px;
      vertical-align: top;
    }
    .brand-name{
      color: #000;
      font-size: 21px;
      padding-right: 10px;
    }
    .brand-discount{
      color: #FF3535;
      font-size:18px
    }
  }
  .view-more{
    cursor: pointer;
    float: right;
    font-size:16px;
    color: #FF3535;
  }
}
.discount-contoiner{
    position: fixed;
    text-align: center;
    left: 50%;
    top: 40%;
    z-index: 99;
    width: 90px;
    margin-left: -695px;
    overflow: hidden;
    transition: all 1s;
    .discount-item{
      border: 1px solid #f3ae92;
      padding: 5px 0;
      text-align: center;
      background: #fff;
      margin-bottom: 5px;
      cursor: pointer;
      &.on{
        background: #ffb060;
      }
    }
}
 
</style>
<style lang="scss">
  .brand-input-box{
    .el-input__inner{
      border: none;
      background: #ebebeb;
      height: 35px;
      line-height: 35px;
    }
  }
</style>

